package com.ssy.wireless.web.controller;

import com.ssy.wireless.entity.ApDevice;
import com.ssy.wireless.entity.ApDeviceTrafficStat;
import com.ssy.wireless.entity.Hotspot;
import com.ssy.wireless.entity.HotspotTrafficStat;
import com.ssy.wireless.web.service.ApDeviceService;
import com.ssy.wireless.web.service.HotspotService;
import com.ssy.wireless.web.vo.req.ApDeviceQueryVo;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by cofey on 16/12/1.
 */
@Controller
@RequestMapping("/export")
public class ExportExcelController extends AbstractController {
    private final static String CHARSET = "iso8859-1";
    @Autowired
    private HotspotService hotspotService;
    @Autowired
    private ApDeviceService apDeviceService;

    @PostMapping("/hotspot")
    public String hotspot(HttpServletResponse response,
                          ApDeviceQueryVo vo) {
        String title = "热点管理";
        String[] header = new String[]{"名称", "位置", "类型", "AP个数", "运行状态", "接入设备数", "上行流量", "下行流量"};
        List<List<String>> list = new ArrayList<>();
        List<Hotspot> hotspots = hotspotService.find(vo.queryParams());
        hotspots.stream().forEach(hp -> {
            List<String> items = new ArrayList<>();
            items.add(hp.getName());
            items.add(hp.getPosition());
            items.add(hp.getType().intValue() == 0 ? "公共区域" : "其他");
            items.add(hp.getApCount().toString());
            items.add(hp.getRunStatus().intValue() == 1 ? "正常" : "故障");
            items.add(hp.getDeviceCount().toString());
            items.add(hp.getUpTraffic().toString());
            items.add(hp.getDownTraffic().toString());
            list.add(items);
        });
        exportExcel(title, header, list, response);
        return null;
    }

    @PostMapping("/hotspot/statistics")
    public String hotspotStatistics(HttpServletResponse response,
                                    @RequestParam(value = "type", defaultValue = "1", required = false) int type,
                                    @RequestParam(value = "beginDate", required = false) String beginDate,
                                    @RequestParam(value = "endDate", required = false) String endDate,
                                    @RequestParam(value = "hotspotId", defaultValue = "0", required = false) Long hotspotId,
                                    @RequestParam(value = "hotspotName", defaultValue = "", required = false) String hotspotName) {
        String title = "热点流量统计信息";
        String[] header = new String[]{"时间", "上行流量", "下行流量"};
        if (null != hotspotId && hotspotId.longValue() > 0l) {
            header = new String[]{"热点", "时间", "上行流量", "下行流量"};
        }
        List<List<String>> list = new ArrayList<>();
        AbstractController.xAxisAndBeginAndEndDate abe = setxAxisAndBeginAndEndDate(type, beginDate, endDate);
        Map<String, Object> params = new HashMap();
        params.put("type", type);
        params.put("begin", abe.getBegin());
        params.put("end", abe.getEnd());
        params.put("hotspotId", null != hotspotId && hotspotId.longValue() > 0l ? hotspotId : null);
        List<HotspotTrafficStat> statistics = hotspotService.findTrafficStatistics(params);
        statistics.stream().forEach(stat -> {
            List<String> items = new ArrayList<>();
            if (null != hotspotId && hotspotId.longValue() > 0l) {
                items.add(hotspotName);
            }
            StringBuilder date = new StringBuilder(stat.getYearVal());
            switch (type) {
                case 1:
                    date = new StringBuilder(stat.getHourVal());
                    date.insert(4, "-");
                    date.insert(7, "-");
                    date.insert(10, " ");
                    break;
                case 2:
                    date = new StringBuilder(stat.getDayVal());
                    date.insert(4, "-");
                    date.insert(7, "-");
                    break;
                case 3:

                    break;
                case 4:
                    date = new StringBuilder(stat.getMonthVal());
                    date.insert(4, "-");
                    break;
                default:
                    date = new StringBuilder(stat.getYearVal());
                    break;
            }
            items.add(date.toString());
            items.add(stat.getUpTraffic().toString());
            items.add(stat.getDownTraffic().toString());
            list.add(items);
        });
        exportExcel(title, header, list, response);
        return null;
    }

    @PostMapping("/ap")
    public String ap(HttpServletResponse response,
                     ApDeviceQueryVo vo) {
        String title = "AP设备运行情况";
        String[] header = new String[]{"AP索引", "IP地址", "MAC地址", "热点名称", "运行状态", "接入设备数(月)", "上行流量", "下行流量"};
        List<List<String>> list = new ArrayList<>();
        List<ApDevice> apDevices = apDeviceService.find(vo.queryParams());
        apDevices.stream().forEach(ap -> {
            List<String> items = new ArrayList<String>();
            items.add(ap.getApIndex());
            items.add(ap.getIp());
            items.add(ap.getMac());
            items.add(ap.getHotspotName());
            items.add(ap.getRunStatus().intValue() == 1 ? "正常" : "故障");
            items.add(ap.getDeviceCount().toString());
            items.add(ap.getUpTraffic().toString());
            items.add(ap.getDownTraffic().toString());
            list.add(items);
        });
        exportExcel(title, header, list, response);
        return null;
    }

    @PostMapping("/ap/statistics")
    public String apStatistics(HttpServletResponse response,
                               @RequestParam(value = "type", defaultValue = "1", required = false) int type,
                               @RequestParam(value = "beginDate", required = false) String beginDate,
                               @RequestParam(value = "endDate", required = false) String endDate,
                               @RequestParam(value = "apDeviceId", defaultValue = "0", required = false) Long apDeviceId,
                               @RequestParam(value = "apDeviceName", defaultValue = "", required = false) String apDeviceName) {
        String title = "AP设备流量统计信息";
        String[] header = new String[]{"时间", "上行流量", "下行流量"};
        if (null != apDeviceId && apDeviceId.longValue() > 0l) {
            header = new String[]{"AP设备", "时间", "上行流量", "下行流量"};
        }
        List<List<String>> list = new ArrayList<>();
        AbstractController.xAxisAndBeginAndEndDate abe = setxAxisAndBeginAndEndDate(type, beginDate, endDate);
        Map<String, Object> params = new HashMap();
        params.put("type", type);
        params.put("begin", abe.getBegin());
        params.put("end", abe.getEnd());
        params.put("apDeviceId", null != apDeviceId && apDeviceId.longValue() > 0l ? apDeviceId : null);
        List<ApDeviceTrafficStat> statistics = apDeviceService.findTrafficStatistics(params);
        statistics.stream().forEach(stat -> {
            List<String> items = new ArrayList<>();
            if (null != apDeviceId && apDeviceId.longValue() > 0l) {
                items.add(apDeviceName);
            }
            StringBuilder date = new StringBuilder(stat.getYearVal());
            switch (type) {
                case 1:
                    date = new StringBuilder(stat.getHourVal());
                    date.insert(4, "-");
                    date.insert(7, "-");
                    date.insert(10, " ");
                    break;
                case 2:
                    date = new StringBuilder(stat.getDayVal());
                    date.insert(4, "-");
                    date.insert(7, "-");
                    break;
                case 3:

                    break;
                case 4:
                    date = new StringBuilder(stat.getMonthVal());
                    date.insert(4, "-");
                    break;
                default:
                    date = new StringBuilder(stat.getYearVal());
                    break;
            }
            items.add(date.toString());
            items.add(stat.getUpTraffic().toString());
            items.add(stat.getDownTraffic().toString());
            list.add(items);
        });
        exportExcel(title, header, list, response);
        return null;
    }

    public void exportExcel(String title, String[] header, List<List<String>> data, HttpServletResponse response) {
        HSSFWorkbook workBook = new HSSFWorkbook();
        HSSFSheet sheet = workBook.createSheet(title);
        HSSFRow headRow = sheet.createRow(0);
        HSSFCell cell = null;
        for (int i = 0; i < header.length; i++) {
            cell = headRow.createCell(i);
            cell.setCellValue(header[i]);
        }
        for (int j = 0; j < data.size(); j++) {
            HSSFRow bodyRow = sheet.createRow(j + 1);
            List<String> items = data.get(j);
            for (int k = 0; k < items.size(); k++) {
                cell = bodyRow.createCell(k);
                cell.setCellValue(items.get(k));
            }
        }
        ServletOutputStream outputStream = null;
        try {
            response.setContentType("application/vnd.ms-excel;charset=" + CHARSET);
            outputStream = response.getOutputStream();
            String fileName = new String((title).getBytes("gbk"), CHARSET);
            response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");
            workBook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
